#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/3/29 11:40
# @Author : 闫峰
# @File    : global_item.py
import time

import requests
from retrying import retry
from third_services.shopee.base_tool import shop_auth, db, shop_auth_shop
from utils.otherutils.json_format import json_format
from utils.times_tool.time_control import count_time

class InterfaceGlobal:
    base_url = "https://partner.shopeemobile.com"
    timestamp = int(time.time())
    partner_id = 2001656

    @retry(stop_max_attempt_number=3, wait_fixed=1000)
    @count_time
    def get_global_item_info(self, ordersourceid, global_item_id_list,
                             apiService="/api/v2/global_product/get_global_item_info"):
        """获取全球商品信息。仅适用于中国大陆卖家和韩国卖家。"""
        sign = shop_auth(ordersourceid, apiService)
        sql1 = """SELECT UserTokenSecretAccessKey,DevIdSellerId  FROM sys_ordersource_authorization WHERE CustomerId=1 AND OrderSourceId=%s;"""
        res1 = db.fetch_all(sql1, (ordersourceid,))
        access_token = res1[0]["UserTokenSecretAccessKey"]
        merchant_id = res1[0]["DevIdSellerId"]
        url = self.base_url + apiService + f"?global_item_id_list={global_item_id_list}"
        payload = {}
        headers = {}
        param = {
            "partner_id": self.partner_id,
            "timestamp": self.timestamp,
            "access_token": access_token,
            "sign": sign,
            "language": "en",
            "merchant_id": merchant_id,
            # "global_item_id_list": item_id_list
        }
        response = requests.request("GET", url, headers=headers, data=payload, params=param, allow_redirects=False)

        return json_format(response.json())

    @retry(stop_max_attempt_number=3, wait_fixed=1000)
    @count_time
    def api_v2_global_product_get_global_item_id(self, ordersourceid, item_id_list, shop_id,
                                                 apiService="/api/v2/global_product/get_global_item_id"):
        """通过item_id获取Get_global_item_id。仅适用于中国大陆卖家和韩国卖家。"""
        sign = shop_auth(ordersourceid, apiService)
        sql1 = """SELECT UserTokenSecretAccessKey,DevIdSellerId  FROM sys_ordersource_authorization WHERE CustomerId=1 AND OrderSourceId=%s;"""
        res1 = db.fetch_all(sql1, (ordersourceid,))
        access_token = res1[0]["UserTokenSecretAccessKey"]
        merchant_id = res1[0]["DevIdSellerId"]
        url = self.base_url + apiService
        payload = {}
        headers = {}
        param = {
            "partner_id": self.partner_id,
            "timestamp": self.timestamp,
            "access_token": access_token,
            "sign": sign,
            "language": "en",
            "merchant_id": merchant_id,
            "item_id_list": item_id_list,
            "shop_id": shop_id
        }
        response = requests.request("GET", url, headers=headers, data=payload, params=param, allow_redirects=False)

        return json_format(response.json())

    @retry(stop_max_attempt_number=3, wait_fixed=1000)
    @count_time
    def api_v2_global_product_get_published_list(self, ordersourceid, global_item_id,
                                                 apiService="/api/v2/global_product/get_published_list"):
        """获取全局项目的已发布项目列表。仅适用于中国大陆卖家和韩国卖家。"""
        sign = shop_auth(ordersourceid, apiService)
        sql1 = """SELECT UserTokenSecretAccessKey,DevIdSellerId  FROM sys_ordersource_authorization WHERE CustomerId=1 AND OrderSourceId=%s;"""
        res1 = db.fetch_all(sql1, (ordersourceid,))
        access_token = res1[0]["UserTokenSecretAccessKey"]
        merchant_id = res1[0]["DevIdSellerId"]
        url = self.base_url + apiService
        payload = {}
        headers = {}
        param = {
            "partner_id": self.partner_id,
            "timestamp": self.timestamp,
            "access_token": access_token,
            "sign": sign,
            "language": "en",
            "merchant_id": merchant_id,
            "global_item_id": global_item_id
        }
        response = requests.request("GET", url, headers=headers, data=payload, params=param, allow_redirects=False)

        return json_format(response.json())

    @retry(stop_max_attempt_number=3, wait_fixed=1000)
    @count_time
    def get_global_item_list(self, ordersourceid, offset=None,
                             apiService="/api/v2/global_product/get_global_item_list"):
        """获取全局项目的已发布项目列表。仅适用于中国大陆卖家和韩国卖家。"""
        sign = shop_auth(ordersourceid, apiService)
        sql1 = """SELECT UserTokenSecretAccessKey,DevIdSellerId  FROM sys_ordersource_authorization WHERE CustomerId=1 AND OrderSourceId=%s;"""
        res1 = db.fetch_all(sql1, (ordersourceid,))
        access_token = res1[0]["UserTokenSecretAccessKey"]
        merchant_id = res1[0]["DevIdSellerId"]
        url = self.base_url + apiService
        payload = {}
        headers = {}
        timestamp = int(time.time())
        param = {
            "partner_id": self.partner_id,
            "timestamp": timestamp,
            "access_token": access_token,
            "sign": sign,
            "merchant_id": merchant_id,
            "page_size": 50
        }
        if offset == None:

            response = requests.request("GET", url, headers=headers, data=payload, params=param, allow_redirects=False)
            response = response.json()
            if response['error'] == 'error_sign':
                raise
            else:
                return response
            # count = 0
            # while True:
            #     count += 1
            #     if count < 100:
            #         print(f"请求get_global_item_list(offset == None)失败{count}次")
            #         if response['error'] == 'error_sign':
            #             response = requests.request("GET", url, headers=headers, data=payload, params=param,
            #                                         allow_redirects=False)
            #             response = response.json()
            #         else:
            #             break
            #     else:
            #         response = {'request_id': '53e6a387a78432a282f02ca16a15bd20', 'error': 'API request timed out',
            #                     'message': 'This app type has no permission to this API.'}
            #         break
            #
            # return response
        else:
            param.update({"offset": offset})

            response = requests.request("GET", url, headers=headers, data=payload, params=param, allow_redirects=False)
            response = response.json()
            if response['error'] == 'error_sign':
                raise
            else:
                return response
            # count = 0
            # while True:
            #     count += 1
            #     print(f"请求get_global_item_list失败{count}次")
            #     if count < 100:
            #
            #         if response['error'] == 'error_sign':
            #             param = {
            #                 "partner_id": self.partner_id,
            #                 "timestamp": int(time.time()),
            #                 "access_token": access_token,
            #                 "sign": shop_auth(ordersourceid, apiService),
            #                 "merchant_id": merchant_id,
            #                 "page_size": 50
            #             }
            #             param.update({"offset": offset})
            #             response = requests.request("GET", url, headers=headers, data=payload, params=param,
            #                                         allow_redirects=False)
            #             response = response.json()
            #         else:
            #             break
            #     else:
            #         response = {'request_id': '53e6a387a78432a282f02ca16a15bd20', 'error': 'API request timed out',
            #                     'message': 'This app type has no permission to this API.'}
            #         break
            # return response

    @retry(stop_max_attempt_number=3, wait_fixed=1000)
    @count_time
    def get_global_model_list(self, ordersourceid, global_item_id,
                              apiService="/api/v2/global_product/get_global_model_list"):
        """获取全局项目的已发布项目列表。仅适用于中国大陆卖家和韩国卖家。"""
        sql1 = """SELECT UserTokenSecretAccessKey,DevIdSellerId  FROM sys_ordersource_authorization WHERE CustomerId=1 AND OrderSourceId=%s;"""
        res1 = db.fetch_all(sql1, (ordersourceid,))
        access_token = res1[0]["UserTokenSecretAccessKey"]
        merchant_id = res1[0]["DevIdSellerId"]
        url = self.base_url + apiService
        payload = {}
        headers = {}
        timestamp = int(time.time())
        param = {
            "partner_id": self.partner_id,
            "timestamp": timestamp,
            "access_token": access_token,
            "sign": shop_auth(ordersourceid, apiService),
            "merchant_id": merchant_id,
            "global_item_id": global_item_id

        }
        response = requests.request("GET", url, headers=headers, data=payload, params=param, allow_redirects=False)
        response = response.json()
        count = 0
        while True:

            if response['error'] == 'error_sign':
                param = {
                    "partner_id": self.partner_id,
                    "timestamp": int(time.time()),
                    "access_token": access_token,
                    "sign": shop_auth(ordersourceid, apiService),
                    "merchant_id": merchant_id,
                    "global_item_id": global_item_id

                }
                count += 1
                print(count)
                response = requests.request("GET", url, headers=headers, data=payload, params=param,
                                            allow_redirects=False)
                response = response.json()
            else:
                break
        return response

    @retry(stop_max_attempt_number=3, wait_fixed=1000)
    @count_time
    def update_stock(self, ordersourceid, apiService="/api/v2/global_product/update_stock"):
        """获取全局项目的已发布项目列表。仅适用于中国大陆卖家和韩国卖家。"""
        sql1 = """SELECT UserTokenSecretAccessKey,DevIdSellerId  FROM sys_ordersource_authorization WHERE CustomerId=1 AND OrderSourceId=%s;"""
        res1 = db.fetch_all(sql1, (ordersourceid,))
        access_token = res1[0]["UserTokenSecretAccessKey"]
        merchant_id = res1[0]["DevIdSellerId"]
        url = self.base_url + apiService
        payload = {
            "global_item_id": 21976253035,
            "stock_list": [{
                "normal_stock": 79
            }]
        }
        headers = {}
        timestamp = int(time.time())
        param = {
            "partner_id": self.partner_id,
            "timestamp": timestamp,
            "access_token": access_token,
            "sign": shop_auth(ordersourceid, apiService),
            "merchant_id": merchant_id

        }
        response = requests.request("POST", url, headers=headers, json=payload, params=param,
                                    allow_redirects=False).json()

        count = 0
        while True:

            if response['error'] == 'error_sign':
                payload = {
                    "global_item_id": 21976253035,
                    "stock_list": [{
                        "normal_stock": 80
                    }]
                }
                headers = {}
                timestamp = int(time.time())
                param = {
                    "partner_id": self.partner_id,
                    "timestamp": timestamp,
                    "access_token": access_token,
                    "sign": shop_auth(ordersourceid, apiService),
                    "merchant_id": merchant_id

                }
                count += 1
                print(count)
                response = requests.request("POST", url, headers=headers, json=payload, params=param,
                                            allow_redirects=False).json()
            else:
                break
        return response

    @retry(stop_max_attempt_number=3, wait_fixed=1000)
    @count_time
    def delete_global_item(self, ordersourceid, global_item_id, apiService="/api/v2/global_product/delete_global_item"):
        """删除全球产品接口"""
        sql1 = """SELECT UserTokenSecretAccessKey,DevIdSellerId  FROM sys_ordersource_authorization WHERE CustomerId=1 AND OrderSourceId=%s;"""
        res1 = db.fetch_all(sql1, (ordersourceid,))
        access_token = res1[0]["UserTokenSecretAccessKey"]
        merchant_id = res1[0]["DevIdSellerId"]
        url = self.base_url + apiService
        payload = {}
        headers = {}
        timestamp = int(time.time())
        param = {
            "partner_id": self.partner_id,
            "timestamp": timestamp,
            "access_token": access_token,
            "sign": shop_auth(ordersourceid, apiService),
            "merchant_id": merchant_id,
            "global_item_id": global_item_id
        }
        response = requests.request("POST", url, headers=headers, data=payload, params=param, allow_redirects=False)
        response = response.json()
        return response


if __name__ == '__main__':
    pass
    # print(InterfaceAll().api_v2_global_product_get_published_list(10544,19578445166))  # 通过渠道id global_item_id 查询刊登的站点店铺
    # res = InterfaceGlobal().get_global_item_list(14224) # 通过渠道id 获取所有的global_item_list
    # print(InterfaceAll().get_global_model_list(10544,18275382322))  # 通过渠道id global_item_id查询model信息   # 变体
    # print(InterfaceAll().get_global_model_list(10544,23532499651))  # 通过渠道id global_item_id查询model信息   # 单体
    print(InterfaceGlobal().get_global_item_info(14296,"20586098315"))  # 查询基本信息
    # print(InterfaceAll().update_stock(14705))
    # res = InterfaceGlobal().api_v2_global_product_get_published_list(13992,19281379639)
    # 15101  18156063195
    # res = InterfaceGlobal().delete_global_item(13942, 18878262034)
    print(res)
